package com.my.netty.promote.server.handler;

import com.my.netty.promote.message.ChatRequestMessage;
import com.my.netty.promote.message.ChatResponseMessage;
import com.my.netty.promote.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@ChannelHandler.Sharable
@Slf4j
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage message) throws Exception {
        log.info("用户单聊消息请求：{}", message);
        String from = message.getFrom();
        String to = message.getTo();

        //找到目标channel
        Channel toCh = SessionFactory.getSession().getChannel(to);
        //接收方在线
        if (toCh != null && toCh.isActive()) {
            toCh.writeAndFlush(new ChatResponseMessage(from, message.getContent()));
        } else {
            //不在线
            ctx.writeAndFlush(new ChatResponseMessage(false, "对方用户不存在或者不在线"));
        }
    }
}
